package com.maxlen.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maxlen.common.constant.MemberConstant;
import com.maxlen.common.utils.*;
import com.maxlen.member.dao.MemberReceiveAddressDao;
import com.maxlen.member.entity.MemberReceiveAddressEntity;
import com.maxlen.member.entity.dto.MemberReceiveAddressEntityDTO;
import com.maxlen.member.service.MemberReceiveAddressService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("memberReceiveAddressService")
public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressDao, MemberReceiveAddressEntity> implements MemberReceiveAddressService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberReceiveAddressEntity> page = this.page(
                new Query<MemberReceiveAddressEntity>().getPage(params),
                new QueryWrapper<MemberReceiveAddressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<MemberReceiveAddressEntity> getAddress(Long memberId) {
        return baseMapper.selectList(new LambdaQueryWrapper<MemberReceiveAddressEntity>().eq(MemberReceiveAddressEntity::getMemberId, memberId));
    }

    @Override
    public MemberReceiveAddressEntity getAddressByAddressId(Long addressId) {
        return baseMapper.selectById(addressId);
    }

    @Override
    @Transactional
    public R addAddress(MemberReceiveAddressEntityDTO memberReceiveAddressEntityDTO) {
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(memberReceiveAddressEntityDTO.getToken());
        if(StringUtils.isBlank(memberIdByJwtToken)){
            return R.error(ResultCode.USER_NOT_LOGIN);
        }

        MemberReceiveAddressEntity memberReceiveAddressEntity = CopyUtils.copy(memberReceiveAddressEntityDTO, MemberReceiveAddressEntity.class);
        memberReceiveAddressEntity.setMemberId(Long.valueOf(memberIdByJwtToken));

        addUpdateAddress(memberReceiveAddressEntityDTO.getDefaultStatus(), Long.valueOf(memberIdByJwtToken));

        int insert = baseMapper.insert(memberReceiveAddressEntity);
        if(insert > 0){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @Override
    public MemberReceiveAddressEntityDTO infoAddress(String addressId) {
        MemberReceiveAddressEntity memberReceiveAddressEntity = baseMapper.selectById(addressId);
        return CopyUtils.copy(memberReceiveAddressEntity, MemberReceiveAddressEntityDTO.class);
    }

    @Override
    @Transactional
    public R updateAddress(MemberReceiveAddressEntityDTO memberReceiveAddressEntityDTO) {
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(memberReceiveAddressEntityDTO.getToken());
        if(StringUtils.isBlank(memberIdByJwtToken)){
            return R.error(ResultCode.USER_NOT_LOGIN);
        }

        if(MemberConstant.MemberReceiveAddress.ADDRESS.getCode().equals(memberReceiveAddressEntityDTO.getDefaultStatus())){
            Long selectCount = baseMapper.selectCount(null);
            if(selectCount == 1){
                return R.error(ResultCode.USER_ADDRESS_ERROR);
            }
        }

        MemberReceiveAddressEntity memberReceiveAddressEntity = CopyUtils.copy(memberReceiveAddressEntityDTO, MemberReceiveAddressEntity.class);

        addUpdateAddress(memberReceiveAddressEntityDTO.getDefaultStatus(), memberReceiveAddressEntityDTO.getMemberId());
        int update = baseMapper.updateById(memberReceiveAddressEntity);
        if(update > 0){
            return R.ok();
        }else{
            return R.error();
        }

    }

    @Override
    @Transactional
    public R setDefaultStatus(String id, String token) {
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(token);
        if(StringUtils.isBlank(memberIdByJwtToken)){
            return R.error(ResultCode.USER_NOT_LOGIN);
        }

        addUpdateAddress(MemberConstant.MemberReceiveAddress.DEFAULT.getCode(), Long.valueOf(memberIdByJwtToken));
        MemberReceiveAddressEntity memberReceiveAddressEntity = baseMapper.selectById(id);
        memberReceiveAddressEntity.setDefaultStatus(MemberConstant.MemberReceiveAddress.DEFAULT.getCode());
        baseMapper.updateById(memberReceiveAddressEntity);
        return R.ok();
    }

    /**
     * 判断如果设置了默认地址，将数据库里设置了默认地址的数据改为普通地址
     * @param defaultStatus 是否是默认地址
     * @param memberId 用户 id
     */
    private void addUpdateAddress(Integer defaultStatus, Long memberId){
        if(MemberConstant.MemberReceiveAddress.DEFAULT.getCode().equals(defaultStatus)) {
            List<MemberReceiveAddressEntity> memberReceiveAddressEntityList = baseMapper.selectList(new LambdaQueryWrapper<MemberReceiveAddressEntity>()
                    .eq(MemberReceiveAddressEntity::getMemberId, memberId)
                    .eq(MemberReceiveAddressEntity::getDefaultStatus, MemberConstant.MemberReceiveAddress.DEFAULT.getCode()));

            if(!memberReceiveAddressEntityList.isEmpty()){
                for (MemberReceiveAddressEntity receiveAddressEntity : memberReceiveAddressEntityList) {
                    receiveAddressEntity.setDefaultStatus(MemberConstant.MemberReceiveAddress.ADDRESS.getCode());
                }
                this.updateBatchById(memberReceiveAddressEntityList);
            }
        }
    }

}
